package system.imp;

import java.io.DataInputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import system.base.ClientDownupfileInfo;
import system.base.Product;
import system.base.ProductCategory;
import system.base.Provider;
import system.base.WarehouseCategory;
import framework.core.*;

/**
 * 导入Excel文件到数据库
 */
public class ExcelWarehouseCategoryToDB implements GWBaseProcesser {
    //start chengbiao.he
    /*加入分类信息*/
    public static String doSaveToDB(DataInputStream aFile, DBConnection con, ILoginContext loginContext, String tableName, String warehouseCode,String upDownType)
            throws GWException

    {
        int tSuccCount = 0;
        int tFailCount = 0;
        String tFailFile = "0";
        HSSFWorkbook tHSSFWorkbook = new HSSFWorkbook();
        //开始读取excel文件
        HSSFSheet tHSSFSheet = null;
        try {
            tHSSFWorkbook = new HSSFWorkbook(aFile);
            tHSSFSheet = tHSSFWorkbook.getSheet(tableName);
        } catch (IOException e) {
            e.getStackTrace();
            new Exception("批量下载文件失败");
        }
        ArrayList alist = new ArrayList();
        ArrayList tsucceslist = new ArrayList();
        ArrayList tErrList = new ArrayList();

        //读取并检查Excel明细
        int tRowCount = parseExcelWarehouseCatory(alist, tHSSFSheet, loginContext);
        if (alist.size() > 0) {
            //保存上传文件到数据库
            for (int i = 0; i < alist.size(); i++) {
                try {
                    GWManufactureUploadVO gwManufactureUpload = (GWManufactureUploadVO) alist.get(i);
                    WarehouseCategory wc = gwManufactureUpload.getWarehouseCategory();

                    //判断数据库中是否存在该条记录
                    //根据仓库编码和分类编码得到是否在数据库中存在该条信息
                    /*
                    Conditions cs = new Conditions();
                    cs.add(WarehouseCategory.WAREHOUSE_CODE,wc.getWarehouseCode());
                    cs.add(WarehouseCategory.CATEGORY_CODE,wc.getCategoryCode());
                    WarehouseCategory warehouseCategory = WarehouseCategory.fetch(con,cs);
                     */

                    WarehouseCategory warehouseCategory = WarehouseCategory.fetch(con, wc.getId());
                    if (warehouseCategory == null) {
                        //数据库中不存在的操作:得到ID = GUID值
                        warehouseCategory = WarehouseCategory.fetch();
                    }

                    //更新当前一条Excel信息数据库
                    warehouseCategory.setWarehouseCode(wc.getWarehouseCode());
                    warehouseCategory.setWarehouseName(wc.getWarehouseName());
                    warehouseCategory.setCategoryCode(wc.getCategoryCode());
                    warehouseCategory.setCategoryName(wc.getWarehouseName());
                    warehouseCategory.setParentCategoryCode(wc.getParentCategoryCode());
                    warehouseCategory.setStatus(wc.getStatus());
                    warehouseCategory.setCreateUserId(wc.getCreateUserId());
                    warehouseCategory.setCreateUser(wc.getCreateUser());
                    warehouseCategory.setCreateTime(wc.getCreateTime());
                    warehouseCategory.setLastUpdateUserId(wc.getLastUpdateUserId());
                    warehouseCategory.setLastUpdateUser(wc.getLastUpdateUser());
                    warehouseCategory.setLastUpdateTime(wc.getLastUpdateTime());
                    warehouseCategory.save(con);
                    tSuccCount++;
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                    tFailCount++;
                }
            }
            //在循环结束后在客户上传下载表中记录操作信息
            try {
                ClientDownupfileInfo clientDownupfileInfo = new ClientDownupfileInfo();
                ClientDownupfileInfo cdfi = ClientDownupfileInfo.fetch();
                cdfi.setCreateTime(new framework.core.DateUtil().getFullString());
                cdfi.setCreateUser(loginContext.getLoginUserName());
                cdfi.setCreateUserId(loginContext.getLoginUserId());
                cdfi.setDownloadtyp(upDownType);
                cdfi.setLastUpdateTime(new framework.core.DateUtil().getDateString());
                cdfi.setLastUpdateUser(loginContext.getLoginUserName());
                cdfi.setLastUpdateUserId(loginContext.getLoginUserId());
                cdfi.setParmsstr(tableName);
                cdfi.setParmstype(ClientDownupfileInfo.UPDOWN_STATE_TEXT);
                cdfi.setDatatableName(tableName);
                cdfi.setStatus(ConstDefine.STR_NAME_VALID_YES);
                cdfi.setUpdownState(ClientDownupfileInfo.UPDOWN_STATE_SUCCESS);
                cdfi.setWarehouseUincode(warehouseCode);
                cdfi.save(con);
            } catch (Exception e) {

            }

        }
        //读取sheet表单
        return tSuccCount + "-" + tFailCount + "-" + tRowCount;
    }

    //end chengbiao.he

    /*start chengbiao.he*/
    //解析Excel文件    
    private static int parseExcelWarehouseCatory(ArrayList aList, HSSFSheet aHSSFSheet, ILoginContext loginContext) throws GWException {
        int i = 0;
        //取得第一行的对象
        HSSFRow tFirstRow = aHSSFSheet.getRow(0);
        DecimalFormat a = new DecimalFormat("#");
        while (true) {
            HSSFRow tHSSFRow = aHSSFSheet.getRow(1 + i);
            boolean flag = false;
            try {

                for (int j = 0; j < 13; j++) {
                    if (tHSSFRow == null) {
                        flag = false;
                        break;
                    }
                    if (tHSSFRow.getCell((short) j) == null) {
                        break;
                    }
                    flag = true;
                    break;
                }
                if (!flag) {
                    break;
                } else {
                    GWManufactureUploadVO tGSManufactureUploadVO = new GWManufactureUploadVO();
                    int tResult = 1;
                    String tFailReason = "";

                    WarehouseCategory wc = new WarehouseCategory();

                    for (int j = 0; j < 13; j++) 
                    {
                        //获得EXCEL首行记录
                        String tFiledName = PoiUtil.getCellValue(tFirstRow, j, "");//tFirstRow.getCell((short) j).getStringCellValue();
                        if (tFiledName == null) tFiledName = ""; 
                        //ID
                        if (tFiledName.equalsIgnoreCase(WarehouseCategory.ID)) {
                            String tID = PoiUtil.getCellValue(tHSSFRow, j, "");//String.valueOf(tHSSFRow.getCell((short) j).getStringCellValue());
                            wc.setId(tID);
                        }
                        //仓库编码
                        else if (tFiledName.equalsIgnoreCase(WarehouseCategory.WAREHOUSE_CODE)) {
                            String tWarehouseCode = PoiUtil.getCellValue(tHSSFRow, j, "");//tHSSFRow.getCell((short) j).getStringCellValue().trim();
                            wc.setWarehouseCode(tWarehouseCode);
                        }
                        //仓库名称
                        else if (tFiledName.equalsIgnoreCase(WarehouseCategory.WAREHOUSE_NAME)) {
                            String tWarehouseName = PoiUtil.getCellValue(tHSSFRow, j, "");//tHSSFRow.getCell((short) j).getStringCellValue().trim();
                            wc.setWarehouseName(tWarehouseName);
                        }
                        //分类编码
                        else if (tFiledName.equalsIgnoreCase(WarehouseCategory.CATEGORY_CODE)) {
                            String tCategoryCode = PoiUtil.getCellValue(tHSSFRow, j, "");//tHSSFRow.getCell((short) j).getStringCellValue().trim();
                            wc.setCategoryCode(tCategoryCode);

                        }
                        //分类名称 
                        else if (tFiledName.equalsIgnoreCase(WarehouseCategory.CATEGORY_NAME)) {
                            String tCategoryName = PoiUtil.getCellValue(tHSSFRow, j, "");//String.valueOf(tHSSFRow.getCell((short) j).getStringCellValue());
                            wc.setCategoryName(tCategoryName);
                        }
                        //上级分类编码 
                        else if (tFiledName.equalsIgnoreCase(WarehouseCategory.PARENT_CATEGORY_CODE)) {
                            String tParentCategoryCode = PoiUtil.getCellValue(tHSSFRow, j, "");//tHSSFRow.getCell((short) j).getStringCellValue().trim();
                            wc.setParentCategoryCode(tParentCategoryCode);

                        }
                        //是否有效 
                        else if (tFiledName.equalsIgnoreCase(WarehouseCategory.STATUS)) {
                            String tStatus = PoiUtil.getCellValue(tHSSFRow, j, "");//tHSSFRow.getCell((short) j).getStringCellValue();
                            wc.setStatus(tStatus);
                        }
                        //创建用户ID
                        else if (tFiledName.equalsIgnoreCase(WarehouseCategory.CREATE_USER_ID)) {
                            String tCreateUserId = PoiUtil.getCellValue(tHSSFRow, j, "");//tHSSFRow.getCell((short) j).getStringCellValue();
                            wc.setCreateUserId(tCreateUserId);
                        }
                        //创建用户
                        else if (tFiledName.equalsIgnoreCase(WarehouseCategory.CREATE_USER)) {
                            String tCreateUser = PoiUtil.getCellValue(tHSSFRow, j, "");;
                            wc.setCreateUser(tCreateUser);
                        }
                        //单证创建时间
                        else if (tFiledName.equalsIgnoreCase(WarehouseCategory.CREATE_TIME)) {
                            String tCreateTime = PoiUtil.getCellValue(tHSSFRow, j, new framework.core.DateUtil().getFullString());//tHSSFRow.getCell((short) j).getStringCellValue();
                            wc.setCreateTime(tCreateTime);
                        }
                        //最后修改人ID  
                        else if (tFiledName.equalsIgnoreCase(WarehouseCategory.LAST_UPDATE_USER_ID)) {
                            String tLastUpdateUserId = PoiUtil.getCellValue(tHSSFRow, j, "");//tHSSFRow.getCell((short) j).getStringCellValue();
                            wc.setLastUpdateUserId(tLastUpdateUserId);
                        }
                        //最后修改人
                        else if (tFiledName.equalsIgnoreCase(WarehouseCategory.LAST_UPDATE_USER)) {
                            String tLastUpdateUser = PoiUtil.getCellValue(tHSSFRow, j, "");//tHSSFRow.getCell((short) j).getStringCellValue().trim();
                            wc.setLastUpdateUser(tLastUpdateUser);
                        }
                        //最后修改时间 
                        else if (tFiledName.equalsIgnoreCase(WarehouseCategory.LAST_UPDATE_TIME)) {
                            String tLastUpdateTime = PoiUtil.getCellValue(tHSSFRow, j, "");//tHSSFRow.getCell((short) j).getStringCellValue();
                            wc.setLastUpdateTime(tLastUpdateTime);
                        }
                    }      
                    tGSManufactureUploadVO.setWarehouseCategory(wc);
                    //tGSManufactureUploadVO.setFailure_reason(tFailReason);
                    tGSManufactureUploadVO.setInsert_result(String.valueOf(tResult));
                    tGSManufactureUploadVO.setRowNumber(i + 1);
                    aList.add(tGSManufactureUploadVO);
                    i++;
                }
            } catch (RuntimeException e) {
                LogWriter.error("****Manufacture BatchImport RuntimeEx :[" + e.getMessage() + "]");
                throw new GWException("导入数据中某一列数据类型不符合规定.");
            } catch (Error e) {
                LogWriter.error("****Manufacture BatchImport ErroeEx :[" + e.getMessage() + "]");
                throw new GWException(e.getMessage());
            } catch (Exception e) {
                LogWriter.error("****Manufacture BatchImport Ex :[" + e.getMessage() + "]");
                throw new GWException(e.getMessage());
            }
        }
        //return i + 2;
        return i;
    }
    /*end chengbiao.he*/
    
}